/*
 * Copyright (c) 2014-2015. Mobiao Group.
 */

package app.controllers;

import app.Const;
import app.models.basic.Attachment;
import app.services.AttachmentMode;
import com.google.common.base.Optional;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.upload.UploadFile;
import goja.Logger;
import goja.StringPool;
import goja.mvc.Controller;
import goja.rapid.storage.FileDto;
import goja.security.shiro.AppUser;
import goja.security.shiro.Securitys;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpStatus;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 * The url attachment Controller.
 * 文件上传处理
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class AttachmentController extends Controller {

    /**
     * The index route.
     * the url /attachment
     * the view in index.ftl.html
     */
    public void index() {
        renderError(HttpStatus.SC_FORBIDDEN);
    }


    /**
     * 上传文件处理
     *
     * 业务模块划分为
     *
     *
     * @see app.services.AttachmentMode
     *
     */
    @Before(POST.class)
    public void upload() {
        // 业务模块
        String filemode = getPara("mode");
        AttachmentMode attachmentMode = AttachmentMode.toModel(filemode);
        if(attachmentMode != AttachmentMode.RES){

            // 必须登录后才能进行上传文件
            if (!Securitys.isLogin()) {
                renderAjaxForbidden();
                return;
            }
        }

        final UploadFile uploadFile = getFile();
        if (uploadFile != null) {
            // 是否删除原来的数据
            String path = getPara("path");
            // 文件名称
            String name = getPara(Const.FIELD_NAME);
            long size = getParaToLong("size");
            final File file = uploadFile.getFile();

            try {
                attachmentMode.delete(path);
                final Optional<FileDto> fileDtoOptional = attachmentMode.storage(file);
                if (fileDtoOptional.isPresent()) {
                    FileDto fileDto = fileDtoOptional.get();
                    final Optional<AppUser<Model>> principal = getPrincipal();
                    AppUser<Model> modelAppUser;
                    if(principal.isPresent()){
                        modelAppUser = principal.get();
                    } else {
                        modelAppUser=  new AppUser<Model>(0,null,null,0,0,null);
                    }
                    Attachment.dao.record(fileDto, modelAppUser, size, name, filemode);
                    renderAjaxSuccess(fileDto);
                } else {
                    renderAjaxFailure();
                }

            } finally {
                try {
                    FileUtils.forceDelete(file);
                } catch (IOException e) {
                    Logger.error("Delete the temporary file upload failed!", e);
                }
            }

        }

    }

    /**
     * 删除单个文件
     */
    @Before(POST.class)
    public void remove() {
        int pk_id = getParaToInt(StringPool.PK_COLUMN, 0);
        String filemode = getPara("mode");
        String path = getPara("path");

        AttachmentMode attachmentMode = AttachmentMode.toModel(filemode);
        // 删除文件
        attachmentMode.delete(path);
        Attachment.dao.deleteById(pk_id);
        renderAjaxSuccess();

    }


    /**
     * 获取多个文件信息
     */
    @Before(GET.class)
    public void multiple() {
        String pks = getPara(Const.PARAM_DATA);
        List<FileDto> attachments = Attachment.dao.findByIds(pks);
        renderAjaxSuccess(attachments);
    }
}